<?php
final class XFileWriter{
	protected $file = null;
	protected $handler = null;
	
	public function __construct(XFile $file){
		$this->file = $file;
		$this->file->create();
		$this->handler = @fopen($file->getPath(), 'w+');
		if($this->handler
			&& !@flock($this->handler, LOCK_EX)){
			@fclose($this->handler);
			$this->handler = null;
		}
	}
	
	public function close(){
		if($this->ready()){
			@flock($this->handler, LOCK_UN);
			@fclose($this->handler);
			$this->handler = null;
		}
	}
		
	public function ready(){
		return !is_null($this->handler) && $this->handler !== false;
	}

	public function write($content, $start = NULL, $length = NULL){
		if(!$this->ready()){
			return false;
		}
		if(!is_null($start)){
			$this->setPosition($start);
		}		
		if(!is_null($length)){
			return @fwrite($this->handler, $content, $length);
		}
		return @fwrite($this->handler, $content);
	}
	
	public function position(){
		if(!$this->ready()){
			return false;
		}
		return ftell($this->handler);
	}
	
	public function setPosition($position){
		if(!$this->ready()){
			return false;
		}
		return @fseek($this->handler, $position, SEEK_SET);
	}
}
?>